import requests, json


class BaiduApi():
    def __init__(self):
        self.API_KEY = "YCaJuTUlE5gVSipx0VbMCSX5"
        self.SECRET_KEY = "GvzXZ5BuqezYgzOYsGrSXF0jeO7SqWml"

    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))

    # 身份证验证
    def idcard(self, picurl):
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()

        # image 可以通过 get_file_content_as_base64("C:\fakepath\1.png",True) 方法获取
        payload = 'id_card_side=front&url=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false' % (
            picurl)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        data = json.loads(response.text)

        dict1 = {
            'name': data['words_result']['姓名']['words'],
            'sex': data['words_result']['性别']['words'],
            'mz': data['words_result']['民族']['words'],
            'birth': data['words_result']['出生']['words'],
            'address': data['words_result']['住址']['words'],
            'code': data['words_result']['公民身份号码']['words']
        }

        return dict1

    # 文字识别
    def fontmessage(self, picurl):
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + self.get_access_token()

        payload = 'url=%s&detect_direction=false&paragraph=false&probability=false' % (picurl)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        data = json.loads(response.text)

        dict1 = {
            'name': data['words_result'][1]['words'],
            'sex': data['words_result'][3]['words'],
            'mz': data['words_result'][5]['words'],
            'birth': data['words_result'][7]['words'],
            'address': data['words_result'][9]['words'],
            'code': data['words_result'][11]['words']
        }

        return dict1





bdapi = BaiduApi()


class Face_Api():
    def __init__(self):
        self.API_KEY = "zihW5me1NV9SJNP0ZzorL5jY"
        self.SECRET_KEY = "sW9UAEykQAzCzTqNoMYFIlmVPInjIJtA"

    def get_access_token(self):
        """
        获取百度api的access_token
        :return: str access_token
        """
        url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}".format(
            self.API_KEY, self.SECRET_KEY)
        res = requests.post(url).json()
        print(res)
        return res['access_token']

    # 人脸识别
    def face(self, img1, img2):
        url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + self.get_access_token()
        payload = json.dumps([
            {
                "image_type": "BASE64",
                "image": img1
            },
            {
                "image_type": "BASE64",
                "image": img2
            }
        ])
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
        data = json.loads(response.text)
        print(data)
        if data['error_msg'] == 'SUCCESS':
            score = data['result']['score']
            return score

face= Face_Api()